package com.brother.template.inflxudb.service;

import com.alibaba.fastjson.JSON;
import com.brother.template.inflxudb.dao.InfluxdbBaseDao;
import com.brother.template.inflxudb.model.Ipassengerflow;
import com.brother.template.util.TimeUtil;
import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.influxdb.dto.Point;
import org.influxdb.dto.Query;
import org.influxdb.dto.QueryResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: xjw
 * @Date: 2018/10/19 16:00
 * @Description:
 */
@Component
public class InfluxdbFlowService {

    private Logger log = LoggerFactory.getLogger(InfluxdbFlowService.class);



    @Autowired
    private InfluxdbBaseDao influxdbBaseDao;

    /**
     * 向 passengerflow 批量插入
     *
     * @param post
     * @return
     */

    public int batchInsertPassengerflow(String url, String dbName, List<Ipassengerflow> post) {
        int result = -1;
        if (!post.isEmpty()) {
            List<Point> insertList = new ArrayList<>();
            for (Ipassengerflow p : post) {
                insertList.add(Point.measurement("passengerflow")
                        .time(TimeUtil.getDateOfString(p.getTime()).getTime(), TimeUnit.MILLISECONDS)
                        .tag("zoneid", p.getZoneId().toString())
                        .addField("countenter", p.getCountEnter())
                        .addField("countexit", p.getCountExit()).build());
            }
            influxdbBaseDao.insert(url, dbName, insertList);
            result = post.size();
        }
        return result;
    }

    /**
     * 向 passengerflow 批量插入
     *
     * @param post
     * @return
     */

    public int batchInsertPassengerflow_business(String url, String dbName, List<Ipassengerflow> post) {
        int result = -1;
        if (!post.isEmpty()) {
            List<Point> insertList = new ArrayList<>();
            for (Ipassengerflow p : post) {
                insertList.add(Point.measurement("passengerflow_business")
                        .time(TimeUtil.getDateOfString(p.getTime()).getTime(), TimeUnit.MILLISECONDS)
                        .tag("zoneid", p.getZoneId().toString())
                        .addField("countenter", p.getCountEnter().intValue())
                        .addField("countexit", p.getCountExit().intValue()).build());
            }
            influxdbBaseDao.insert(url, dbName, insertList);
            result = post.size();
        }
        return result;
    }

    /**
     * 查询出 table 表的数据
     *
     * @param table
     * @param startTime
     * @param endTime
     * @return
     */
    public List<Ipassengerflow> selectflow(String timeZone, String url, String dbName, String table, List<Integer> zoneIds, String startTime, String endTime) {
        List<Ipassengerflow> result = null;
        InfluxDB influxDB = InfluxdbBaseDao.MyInfluxDBUtil.getInfluxDB(url);
        String sqlf = "SELECT * FROM %s where zoneid = '%d' and time>='%s' and time<='%s' order by time tz('%s');";
        StringBuffer sqlBf = new StringBuffer();
        if (!zoneIds.isEmpty()) {
            for (Integer zoneId : zoneIds) {
                sqlBf.append(String.format(sqlf, table, zoneId, startTime, endTime, timeZone));
            }
            QueryResult queryResult = influxDB.query(new Query(sqlBf.toString(), dbName, true));

            result = toIpassengerflow(queryResult);

        }
        return result;

    }


    private List<Ipassengerflow> toIpassengerflow(QueryResult queryResult) {
        List<Ipassengerflow> ilist = null;
        if (!queryResult.hasError()) {
            if (queryResult.getResults().size() >= 1) {
                List<QueryResult.Series> series = queryResult.getResults().get(0).getSeries();
                if (series != null) {

                    StringBuffer sb = new StringBuffer("[");
                    for (QueryResult.Series qs : series) {
                        List<String> columns = qs.getColumns();
                        String zoneid = null;
                        if (qs.getTags() != null) {
                            zoneid = qs.getTags().get("zoneid");
                        }

                        List<List<Object>> values = qs.getValues();
                        for (List<Object> v : values) {
                            for (int i = 0; i < columns.size(); i++) {
                                String va = v.get(i).toString();
                                if (va.indexOf("+") > 0) {
                                    va = va.substring(0, va.indexOf("+")).replaceAll("T", " ").trim();
                                }

                                if (i == 0) {
                                    if (zoneid == null) {
                                        sb.append("{\"" + columns.get(i) + "\":\"" + va + "\",");
                                    } else {
                                        sb.append("{\"zoneid\":\"" + Integer.parseInt(zoneid) + "\",\"" + columns.get(i) + "\":\"" + va + "\",");
                                    }
                                } else if (i == (columns.size() - 1)) {
                                    sb.append("\"" + columns.get(i) + "\":\"" + va + "\"},");
                                } else {
                                    sb.append("\"" + columns.get(i) + "\":\"" + va + "\",");
                                }

                            }
                        }

                    }
                    sb.append("]");
                    ilist = JSON.parseArray(sb.toString(), Ipassengerflow.class);

                } else {
                    log.info("==== no data");
                }
            } else {
                log.info("==== no data");
            }
        } else {
            log.error(queryResult.getError());
        }

        return ilist;
    }

}
